﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;


namespace ICodeShare.UI.Controls.Core.Converters
{

    public class BackgroundToBorderBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var solidColorBrush = value as SolidColorBrush;
            if (solidColorBrush == null) return null;

            var backgroundColor = solidColorBrush.Color;

            var brightness = Brightness(backgroundColor);

            return new SolidColorBrush(Lerp(backgroundColor,Colors.Black, brightness > 150 ? 0.3f : 0f));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }

        /// <summary>
        /// 计算RGB颜色的平方根,用于确定颜色的黑色色调，值小于150为偏白色，值大于150为偏黑色
        /// </summary>
        /// <param name="accentColor">主题颜色</param>
        /// <returns></returns>
        private  int Brightness(Color accentColor)
        {
            return (int)Math.Sqrt(accentColor.R * accentColor.R * .241 + accentColor.G * accentColor.G * .691 + accentColor.B * accentColor.B * .068);
        }

        /// <summary>
        /// 计算两种颜色的混合颜色
        /// </summary>
        /// <param name="colour"></param>
        /// <param name="to"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        private Color Lerp(Color colour, Color to, float amount)
        {
            // start colours as lerp-able floats
            float sr = colour.R, sg = colour.G, sb = colour.B;

            // end colours as lerp-able floats
            float er = to.R, eg = to.G, eb = to.B;

            // lerp the colours to get the difference
            byte r = (byte)Lerp(sr,er, amount),
                 g = (byte)Lerp(sg,eg, amount),
                 b = (byte)Lerp(sb,eb, amount);

            // return the new colour
            return Color.FromArgb(colour.A, r, g, b);
        }

        /// <summary>
        /// 计算两种颜色的RGB值的合成
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public  float Lerp(float start, float end, float amount)
        {
            float difference = end - start;
            float adjusted = difference * amount;
            return start + adjusted;
        }
    }
}
